<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/11
 * Time: 9:04
 */
namespace App\Libs\Aliyuncs;

use App\Libs\Aliyuncs\Aliyunphpsdkcore\DefaultAcsClient;
use App\Libs\Aliyuncs\Aliyunphpsdkcore\Profile\DefaultProfile;
use App\Libs\Aliyuncs\Aliyunphpsdkgreen\Green\Request\V20170825\ImageSyncScanRequest;
use App\Libs\Aliyuncs\Aliyunphpsdkgreen\Green\Request\V20170825\TextScanRequest;
use Illuminate\Support\Facades\Log;

class GreenDection {
    protected $iClientProfile;
    public function __construct(){
        include_once 'Aliyunphpsdkcore/Config.php';
        date_default_timezone_set("PRC");
        // 请替换成您自己的accessKeyId、accessKeySecret
        $iClientProfile = DefaultProfile::getProfile("cn-shanghai", env('Green_AccessKeyID'), env('Green_AccessKeySecret'));
        $this->iClientProfile = $iClientProfile;
        DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
    }

    /**
     * @param $image
     * @return bool
     * @throws \Exception
     */
    public function imageSyncScan($image){
        $client = new DefaultAcsClient($this->iClientProfile);
        $request = new ImageSyncScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");
        /*$task1 = array('dataId' =>  uniqid(),
            'url' => 'http://bangz.oss-cn-hangzhou.aliyuncs.com/h5/task/1_1527762220.wx0bbe95edd2d5c47e.o6zAJs-I-Fs5muQbMATXbd6bDXGk.88cd64e8c79810c4703a0edb1fa88d8e.jpg',
            'time' => round(microtime(true)*1000)
        );*/
        $task = array();
        if(is_array($image)) {
            foreach ($image as $key=>$value) {
                $task[] = array(
                    'dataId' =>  uniqid(),
                    'url' => $value,
                    'time' => round(microtime(true)*1000)
                );
            }
        }else{
            $task[] = array(
                'dataId' =>  uniqid(),
                'url' => $image,
                'time' => round(microtime(true)*1000)
            );
        }
        // 支持的场景有：porn（色情）、terrorism（暴恐）、qrcode（二维码）、ad（图片广告）、 ocr（文字识别）
        //var_dump($task);
        $request->setContent(json_encode(array("tasks" => $task,
            "scenes" => array("porn",'terrorism'))));
        try {
            $response = $client->getAcsResponse($request);
            //var_dump($response);
            Log::info(var_export($response,true));
            if(200 == $response->code){
                $taskResults = $response->data;
                foreach ($taskResults as $taskResult) {
                    if(200 == $taskResult->code){
                        $sceneResults = $taskResult->results;
                        foreach ($sceneResults as $sceneResult) {
                            $scene = $sceneResult->scene;
                            $suggestion = $sceneResult->suggestion;
                            // 根据scene和suggetion做相关处理
                            // do something
                            if($suggestion != 'pass'){
                                return false;
                            }
                        }
                    }else{
                        throw new \Exception("task process fail:" . $response->code,$response->code);
                    }
                }
            }else{
                throw new \Exception("detect not success. code:" . $response->code,$response->code);
            }
        } catch (\Exception $e) {
           throw new \Exception($e->getMessage(),$e->getCode());
        }
        return true;
    }

    /**
     *
     * @param $contents
     * @return bool
     * @throws \Exception
     */
    public function textScan($contents) {

        $client = new DefaultAcsClient($this->iClientProfile);

        $request = new TextScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        $task1 = array(
            'dataId' =>  uniqid(),
            'content' => $contents
        );
        /**
         * 文本垃圾检测： antispam
         * 关键词检测： keyword
         **/
        $request->setContent(
            json_encode(array("tasks" => array($task1), "scenes" => array("antispam")))
        );

        try {
            $response = $client->getAcsResponse($request);
            Log::info(var_export($response,true));
            //print_r($response);
            if(200 == $response->code){
                $taskResults = $response->data;
                Log::info('detection result:'.json_encode($taskResults,JSON_UNESCAPED_UNICODE));
                foreach ($taskResults as $taskResult) {
                    if(200 == $taskResult->code){
                        $sceneResults = $taskResult->results;
                        foreach ($sceneResults as $sceneResult) {
                            $scene = $sceneResult->scene;
                            $suggestion = $sceneResult->suggestion;
                            //根据scene和suggetion做相关处理
                            //do something
                           if($suggestion != 'pass') {
                               Log::info('detecttion_info:'.json_encode($sceneResults,JSON_UNESCAPED_UNICODE));
                                return false;
                           }
                        }
                    }else{
                       throw new \Exception("task process fail:" . $response->code,$response->code);
                    }
                }
            }else{
               throw new \Exception("detect not success. code:" . $response->code,$response->code);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(),$e->getCode());
        }
        return true;
    }
}